package com.whlilong.jxc.editor.support;

import java.util.List;

import org.eclipse.jface.viewers.TextCellEditor;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.widgets.Composite;

import com.whlilong.jxc.listener.IEditorListener;
import com.whlilong.jxc.listener.IModifyListener;
import com.whlilong.jxc.model.Keshang;
import com.whlilong.jxc.sys.ExtentionInfo;

public class DistrictTextKeyCellEditor extends TextCellEditor {
	protected IEditorListener listener;
	private int currentColumn;
	private String oldString;//初始化值
	private IModifyListener modify;

	public DistrictTextKeyCellEditor(Composite parent,IEditorListener listener,int column,IModifyListener modify) {
		super(parent, SWT.SINGLE);
		this.listener = listener;
		this.currentColumn = column;
		this.modify = modify;
	}

	public void releaseKey() {
		fireApplyEditorValue();
		deactivate();
	}
	
	@Override
	protected void fireApplyEditorValue() {
		super.fireApplyEditorValue();
		this.modify.modify();
	}

	@Override
	protected void editOccured(ModifyEvent e) {
		listener.noticeSuccess();
		if(isSave()){
		  super.editOccured(e);
		}
	}
	
	private boolean isSave(){
		if(currentColumn==2){//编号
			return judgeID();
		}
		return true;
	}
	@SuppressWarnings("unchecked")
	protected boolean judgeID(){
		String str = text.getText();
		List<Keshang> list = ExtentionInfo.getInstance().getKeshanginfo();
		String regex = "[0-9]*";
		if (str!=null && !str.equals("")) {
			if (str.matches(regex)) {
				for (int k = 0; k < list
						.size(); k++) {
					if (!str.equals(oldString) && list.get(k)
							.getKeshangid()
							.equals(str)) {
						listener.noticeFault("错误：客商编号重复，数据不能保存！");
						str = "";
						text.setToolTipText("编号重复");
						text.setText(str);
						return false;
					}
				}
			} else {
				listener.noticeFault("错误：请输入数字作为客商ID！");
				str = "";
				text.setToolTipText("编号非法");
				text.setText(str);
				return false;
			}
		} else {
			listener.noticeFault("错误：请输入正确的品牌编号(非重复的数字编号)！");
			return false;
		}
		text.setToolTipText("");
		return true;
	}
	public String getOldString() {
		return oldString;
	}

	public void setOldString(String oldString) {
		this.oldString = oldString;
	}
}
